package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.domain.Service;
import org.csu.mypetstore.persistence.AccountMapper;
import org.csu.mypetstore.result.Result;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.ServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.security.MessageDigest;
import java.util.List;
import java.util.Objects;

@Controller
public class AccountController {
    @Autowired
    AccountService accountService;
    @Autowired
    ServiceService serviceService;

    static String oldname;
    static String oldId;

    @CrossOrigin
    @PostMapping(value = "api/login")
    @ResponseBody
    public Result login(@RequestBody Account requestUser) {
        // 对 html 标签进行转义，防止 XSS 攻击
        String username = requestUser.getUsername();
        username = HtmlUtils.htmlEscape(username);

        if (Objects.equals("admin", username) && Objects.equals("123456", requestUser.getPassword()) || serviceService.getServiceByIdAndPsw(username,requestUser.getPassword()) != null) {
            return new Result(200);
        } else {
            String message = "账号密码错误";
            System.out.println("test");
            return new Result(400);
        }
    }
    @CrossOrigin
    @PostMapping(value = "api/editUser")
    @ResponseBody
    public String edit(@RequestBody String quest){
        //
        //System.out.println(quest);
        String[] array=  quest.split("\\.");
        //发送用户信息,按照name,usernumber,money,like,date,reciever,address,phonenumber,password格式发送
        JSONObject jsonObject = JSON.parseObject(quest);
        System.out.println(jsonObject);
//jsonObject.getString("params")
        if(jsonObject.getString("params").equals("getUser")){
            List<Account> accountList = accountService.getAccountList();
            String ret = "";
            for (int i = 0; i<accountList.size(); i++){
                Account account = accountList.get(i);
                ret += account.getUsername() + ",";
                ret += account.getPhonenumber() + ",";
                ret += "1231,";
                ret += account.getFavouriteCategoryId() + ",";
                ret += "1,";
                ret += account.getLastName() + ",";
                ret += account.getFirstName() + ",";
                ret += account.getCountry()+" " + account.getState()+" " + account.getCity() + ",";
                ret += account.getAddress1() + ",";
                ret += account.getPhoneInUse() + ",";
                if (i != accountList.size() - 1) ret += ",";
            }
            System.out.println(ret);
            return ret;


            //return "张三,15211146746,123,狗,2019-3-3,老张,黑龙江省哈尔滨市道里区,巴啦啦街道001，16666666666,123321,李四,17888262503,321,猫,2019-4-6,老李头,湖南省长沙市,2333333333,321123";
        }
        //删除某用户
        if(jsonObject.getString("params").equals("del"))
        {
            String username = jsonObject.getString("username");
            accountService.deleteAccount(username);
            accountService.deleteSignon(username);
            accountService.deleteProfile(username);
            //前端会将用户姓名传过来,删除相应用户
            return "ok";
        }

        if(jsonObject.getString("params").equals("ediUserbyName")){
            oldname = jsonObject.getString("username");
            return "";
        }


        //修改用户信息
        if(jsonObject.getString("params").equals("editUserInfo"))
        {
            boolean flag;
            System.out.println(quest);
            System.out.println(oldname);
            if (!jsonObject.getString("name").equals(oldname)){
                if (accountService.getAccountByUserid(jsonObject.getString("name")) != null){
                    System.out.println("fail");
                    flag = false;
                }else{
                    flag = true;
                }
            }else{
                flag = true;
            }
            if (flag){
                System.out.println(jsonObject.getString("recieveraddress"));
                String recieveraddress = jsonObject.getString("recieveraddress");
                String array1[] = recieveraddress.split("\"");
                String country,city,state;
                if (array1.length != 1){
                    System.out.println(array1[1] + array1[3] + array1[5]);
                    country = array1[1];
                    state = array1[3];
                    city = array1[5];
                }else {
                    String array2[] = recieveraddress.split("\\s");
                    System.out.println(array2[0] + array2[1] + array2[2]);
                    country = array2[0];
                    state = array2[1];
                    city = array2[2];
                }

                Account account = new Account();
                account.setOldname(oldname);
                account.setUsername(jsonObject.getString("name"));

                String password = jsonObject.getString("password");

                if (password != "") {
                    System.out.println(password);
                    //加密
                    MessageDigest md5 = null;
                    try {
                        md5 = MessageDigest.getInstance("MD5");
                    } catch (Exception e) {
                        System.out.println(e.toString());
                        e.printStackTrace();
                        return "";
                    }
                    char[] charArray = password.toCharArray();
                    byte[] byteArray = new byte[charArray.length];

                    for (int i = 0; i < charArray.length; i++)
                        byteArray[i] = (byte) charArray[i];
                    byte[] md5Bytes = md5.digest(byteArray);
                    StringBuffer hexValue = new StringBuffer();
                    for (int i = 0; i < md5Bytes.length; i++) {
                        int val = ((int) md5Bytes[i]) & 0xff;
                        if (val < 16)
                            hexValue.append("0");
                        hexValue.append(Integer.toHexString(val));
                    }

                    String newPassword = hexValue.toString();
                    System.out.println(newPassword);
                    account.setPassword(newPassword);
                }
                account.setAddress1(jsonObject.getString("detailedaddress"));
                account.setPhonenumber(jsonObject.getString("userphonenumber"));
                account.setPhoneInUse(jsonObject.getString("recieverphonenumber"));
                account.setCity(city);
                account.setCountry(country);
                account.setState(state);
                account.setFirstName(jsonObject.getString("reciever_f"));
                account.setLastName(jsonObject.getString("reciever_l"));
                accountService.updateAccount(account);
                if (password != ""){ accountService.updateSignon(account);}
                else {accountService.updateSignonNoPsw(account);}
                accountService.updateProfile(account);
                accountService.updateOrders(account);
                return "editUserInfoOk";
            }else{
                return "用户名已存在";
            }
            //前端会将信息以json数组传过来



        }
        //通过用户名进行搜索
        if(jsonObject.getString("params").equals("searchbyUsername"))
        {
            String keyword = jsonObject.getString("name");
            List<Account> accountList = accountService.searchAccountList(keyword);
            String ret = "";
            for (int i = 0; i<accountList.size(); i++){
                Account account = accountList.get(i);
                ret += account.getUsername() + ",";
                ret += account.getPhonenumber() + ",";
                ret += "1231,";
                ret += account.getFavouriteCategoryId() + ",";
                ret += "1,";
                ret += account.getLastName() + ",";
                ret += account.getFirstName() + ",";
                ret += account.getCountry()+" " + account.getState()+" " + account.getCity() + ",";
                ret += account.getAddress1() + ",";
                ret += account.getPhoneInUse() + ",";
                if (i != accountList.size() - 1) ret += ",";
            }
            System.out.println(ret);
            return ret;
            //会将用户名发过来
            //按照name,usernumber,money,like,date,reciever,address,phonenumber,password格式发送
            //return "张三,152777777,123,狗,2019-3-3,老张,黑龙江省哈尔滨市,16666666666,123321";
        }
//        //创建新用户
//        if(jsonObject.getString("params").equals("newUser"))
//        {
//            System.out.println(quest);
//            if (accountService.getAccountByUserid(jsonObject.getString("name")) != null){
//                System.out.println("no");
//                return "newFail";
//            }else {
//                Account account = new Account();
//                account.setPassword(jsonObject.getString("password"));
//                account.setUsername(jsonObject.getString("name"));
//                accountService.newAcount(account);
//                accountService.newSignon(account);
//                accountService.newProfile(account);
//                return "newSuccess";
//            }
//            //会将用户名和密码发过来
//            //如果用户名和手机号没有问题那么可以注册，返回注册成功信息，如果有问题则返回失败信息
//            //return "newFail";
//        }
        else{
            System.out.println("error");
            return "";
        }
    }
    @CrossOrigin
    @PostMapping(value = "api/editAccount")
    @ResponseBody
    public String editAccount(@RequestBody String quest) {

        String[] array=  quest.split("\\.");
        JSONObject jsonObject = JSON.parseObject(quest);
        System.out.println(jsonObject);

        //获取客服信息
        if(jsonObject.getString("params").equals("getAccount"))
        {
            List<Service> serviceList = serviceService.getServiceList();
            String ret = "";
            for (int i=0; i<serviceList.size(); i++){
                Service service = serviceList.get(i);
                ret += service.getName() + ",";
                ret += service.getId() + ",";
                ret += service.getDate() + ",";
                ret += service.getPhone();
                if (i != serviceList.size()-1) {ret += ",";}
            }
            //按照"姓名，账号ID，入职日期,手机号码"返回
            System.out.println(ret);
            return ret;
            //return "小张,balala,2019-3-5,15211146746,靓仔,lalaba,2019-7-5,150461233369";
        }
        boolean flag;
        //修改客服信息
        if(jsonObject.getString("params").equals("editServer"))
        {
            if (!jsonObject.getString("name").equals(oldId)){
                if (serviceService.getServiceById(jsonObject.getString("name")) != null){
                    flag = false;
                }else{
                    flag = true;
                }
            }else{
                flag = true;
            }
            if (flag) {
                Service service = new Service();
                service.setOldId(jsonObject.getString("id"));
                service.setId(jsonObject.getString("id"));
                service.setName(jsonObject.getString("name"));
                service.setDate(jsonObject.getString("date"));
                service.setPhone(jsonObject.getString("phonenumber"));
                if (jsonObject.getString("password") == null) {
                    serviceService.updateServiceNoPassword(service);
                } else {
                    service.setPassword(jsonObject.getString("password"));
                    serviceService.updateService(service);
                }
                //！！！！需要看密码是否为空，如果为空就是没修改，不为空就是修改了，这里需要注意
                System.out.println(quest);
                return "editSuccess";
            }else {
                System.out.println("no");
                return "editFail";
            }
        }
        //新增客服信息
        if(jsonObject.getString("params").equals("newServer"))
        {
            if (serviceService.getServiceById(jsonObject.getString("id")) != null || jsonObject.getString("id").equals("admin")){
                System.out.println("no");
                return "newServerFail";
            }else {
                Service service = new Service();
                service.setName(jsonObject.getString("name"));
                service.setId(jsonObject.getString("id"));
                service.setPhone(jsonObject.getString("phonenumber"));
                service.setDate(jsonObject.getString("date"));
                service.setPassword(jsonObject.getString("password"));
                serviceService.newService(service);
                return "newServerSuccess";
            }
        }
        //删除客服信息
        if(jsonObject.getString("params").equals("del"))
        {
            serviceService.deleteService(jsonObject.getString("id"));
            //System.out.println(quest);
            return "ok";
        }
        else{
            System.out.println("error");
            return "";
        }
    }
}
